using System.Windows;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using MiniTheme.Services;
using MiniTheme.ViewModels;
using MiniTheme.Models;
using MiniTheme.Services.Interfaces;
using MiniTheme.Views;
using MiniTheme.Views.Pages;

namespace MiniTheme;

// 应用程序主类，负责初始化和配置
public partial class App : Application
{  
    // 应用程序宿主
    // 其他地方使用容器直接注入IServiceProvider
    private readonly IHost _host; 
    public App()
    {
        var builder = Host.CreateApplicationBuilder();
        // 配置配置源
        builder.Configuration.Sources.Clear();
        builder.Configuration
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
        // 配置 Options 模式
        builder.Services.Configure<AppSettings>(
            builder.Configuration.GetSection(AppSettings.SectionName));
        // 注册服务
        builder.Services.AddSingleton<IConfigService, ConfigService>();
        builder.Services.AddSingleton<IThemeService, ThemeService>();
        builder.Services.AddSingleton<ISystemThemeMonitor, SystemThemeMonitor>();
        builder.Services.AddSingleton<ILanguageService, LanguageService>();
        builder.Services.AddSingleton<INavigationService, NavigationService>();
        // 注册后台服务
        builder.Services.AddHostedService<ApplicationHostService>();
        // 注册视图
        builder.Services.AddTransient<ThemeView>();
        builder.Services.AddTransient<LanguageView>();
        builder.Services.AddTransient<ControlsView>();
        // 注册 ViewModels
        builder.Services.AddSingleton<MainViewModel>();
        builder.Services.AddTransient<ThemeViewModel>();
        builder.Services.AddTransient<LanguageViewModel>();
        builder.Services.AddTransient<ControlsViewModel>();
        // 注册窗口
        builder.Services.AddSingleton<MainWindow>();
        _host = builder.Build();
    }

    protected override async void OnStartup(StartupEventArgs e)
    {
        await _host.StartAsync();
        //初始化(主题,语言,窗口)移动到applicationhostservice里面了
        base.OnStartup(e);
    }
    protected override async void OnExit(ExitEventArgs e)
    {
        await _host.StopAsync();
        _host.Dispose();
        base.OnExit(e);
    }
}